const dayjs = require('dayjs');
/**
 * Notes: 工作流模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-06-24 07:48:00 
 */

const BaseBiz = require('../config/base_biz_config.js');
const projectSetting = require('../../../config/projects_config.js');
const pageHelper = require('../../../helpers/page_helper.js');
const fileHelper = require('../../../helpers/file_helper.js');
const cloudHelper = require('../../../helpers/cloud_helper.js');
const cacheHelper = require('../../../helpers/cache_helper.js');
const constants = require('../../../constants/constants.js');
const PassportBiz = require('../config/passport_biz_config.js');

class FlowBiz extends BaseBiz {

	static async openFlowFile(e, that) {
		let idx = pageHelper.dataset(e, 'idx');
		let node = that.data.flow.FLOW_OBJ.file[idx];
		return fileHelper.openFile(node);
	}

	// 分类菜单
	static getCateMenu(name = '') {
		let sortItems = [{ label: name || '分类', type: 'cateId', value: '' }];

		let allSteps = projectSetting.FLOW_ALL_STEPS;
		for (let k = 0; k < allSteps.length; k++) {
			sortItems.push({ label: allSteps[k].FLOW_NAME, type: 'cateId', value: allSteps[k].FLOW_CATE_ID });
		}

		return sortItems;
	}

	static async loadDetail(that) {
		if (!that || typeof that.setData !== 'function') {
			console.error('参数错误：that对象无效');
			return;
		}

		let id = that.data.id;
		console.log('开始加载流程详情，原始ID:', id);

		// ID格式验证和处理
		if (typeof id === 'object' && id._id) {
			id = id._id;
			console.log('ID是对象格式，提取后:', id);
		}

		if (!id) {
			console.error('流程ID为空');
			that.setData({
				isLoad: true,
				flow: null
			});
			pageHelper.showModal('未找到流程ID');
			return;
		}

		// 先显示加载中
		that.setData({
			isLoad: false
		});

		try {
			console.log('准备调用云函数，ID:', id);
			let flow = await cloudHelper.callCloudData('flow/view', { id });
			
			if (!flow) {
				console.error('未找到流程数据');
				that.setData({
					isLoad: true,
					flow: null
				});
				pageHelper.showModal('未找到流程数据');
				return;
			}

			console.log('获取到流程数据:', flow);

			// 不再在这里严格验证FLOW_CATE_ID，改为更灵活的方式
			// 查找对应的步骤
			let curStep = null;
			let cateId = flow.FLOW_CATE_ID || '';
			
			try {
				let allSteps = projectSetting.FLOW_ALL_STEPS;
				
				// 通过FLOW_CATE_ID匹配
				if (cateId) {
					for (let k = 0; k < allSteps.length; k++) {
						if (allSteps[k].FLOW_CATE_ID == cateId) {
							curStep = allSteps[k];
							console.log('匹配到步骤:', curStep.FLOW_NAME);
							break;
						}
					}
				}
				
				// 如果没找到，尝试通过名称匹配
				if (!curStep && flow.FLOW_CATE_NAME) {
					for (let k = 0; k < allSteps.length; k++) {
						if (allSteps[k].FLOW_NAME == flow.FLOW_CATE_NAME) {
							curStep = allSteps[k];
							console.log('通过名称匹配到步骤:', curStep.FLOW_NAME);
							// 更新缺失的分类ID
							if (!cateId) {
								cateId = curStep.FLOW_CATE_ID;
								flow.FLOW_CATE_ID = cateId;
								console.log('通过名称补充了分类ID:', cateId);
							}
							break;
						}
					}
				}
				
				// 如果还是没找到，使用第一个
				if (!curStep && allSteps.length > 0) {
					curStep = allSteps[0];
					console.log('使用默认步骤:', curStep.FLOW_NAME);
					// 更新缺失的分类ID
					if (!cateId) {
						cateId = curStep.FLOW_CATE_ID;
						flow.FLOW_CATE_ID = cateId;
						console.log('使用默认步骤补充了分类ID:', cateId);
					}
				}
			} catch (err) {
				console.error('获取流程步骤失败:', err);
			}

			// 获取表单字段
			let fields = null;
			if (curStep && curStep.FLOW_FIELDS) {
				fields = curStep.FLOW_FIELDS;
				console.log('从步骤获取到字段:', fields.length);
			} else if (flow.FLOW_FORMS) {
				// 从现有表单反向构建字段
				fields = [];
				let forms = flow.FLOW_FORMS;
				for (let i = 0; i < forms.length; i++) {
					fields.push({
						mark: forms[i].mark,
						title: forms[i].title,
						type: forms[i].type,
						must: false
					});
				}
				console.log('从表单构建出字段:', fields.length);
			}

			// 更新页面数据
			that.setData({
				flow,
				curStep,
				fields,
				cateId,
				isLoad: true
			});

			// 更新导航栏标题
			if (curStep) {
				wx.setNavigationBarTitle({
					title: '申请单修改 - ' + curStep.FLOW_NAME
				});
			}

		} catch (err) {
			console.error('加载流程详情失败:', err);
			that.setData({
				isLoad: true,
				flow: null
			});
			pageHelper.showModal(err.message || '加载失败，请重试');
		}
	}

	// 创建一个虚拟的flow对象用于调试
	static _createDummyFlow(options) {
		try {
			let cateId = options.cateId;
			if (!cateId) return null;
			
			let allSteps = projectSetting.FLOW_ALL_STEPS;
			let cateName = '';
			
			for (let k = 0; k < allSteps.length; k++) {
				if (allSteps[k].FLOW_CATE_ID == cateId) {
					cateName = allSteps[k].FLOW_NAME;
					break;
				}
			}
			
			return {
				_id: 'dummy_' + cateId,
				FLOW_CATE_ID: cateId,
				FLOW_CATE_NAME: cateName,
				FLOW_FORMS: [],
				FLOW_OBJ: {
					title: cateName + '申请',
					person: '',
					phone: ''
				},
				IS_DUMMY: true // 标记为虚拟数据
			};
		} catch (err) {
			console.error('创建虚拟流程数据出错:', err);
			return null;
		}
	}

	static initFormData(id = '', cateId) {
		// 标准化cateId
		const normalizedCateId = String(cateId || '').trim();
		const numericCateId = parseInt(normalizedCateId, 10);
		
		console.log('initFormData - 处理表单数据:', 
			'cateId:', cateId, 
			'normalized:', normalizedCateId, 
			'numeric:', numericCateId);
		
		// 默认基础表单字段
		const defaultFields = [
			{ mark: 'title', title: '标题', type: 'text', must: true, len: 50, def: '' },
			{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
			{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
			{ mark: 'desc', title: '申请说明', type: 'textarea', must: true, len: 500, def: '' }
		];
		
		let fields = null;
		let allSteps = projectSetting.FLOW_ALL_STEPS || [];
		
		// 增强匹配逻辑
		for (let k = 0; k < allSteps.length; k++) {
			const stepId = allSteps[k].FLOW_CATE_ID;
			const stepIdStr = String(stepId).trim();
			const stepIdNum = parseInt(stepIdStr, 10);
			
			// 使用多种匹配方式
			if (
				stepId == cateId || // 直接比较（宽松相等）
				stepIdStr === normalizedCateId || // 字符串精确比较
				stepIdNum === numericCateId || // 数字比较
				(normalizedCateId === '0' && stepIdStr === '') || // 处理空字符串作为0的情况
				(stepIdStr === '0' && normalizedCateId === '') // 处理空字符串作为0的情况
			) {
				// 如果找到了匹配的步骤，使用其字段定义
				fields = allSteps[k].FLOW_FIELDS;
				console.log('initFormData - 找到匹配的审批类型:', allSteps[k].FLOW_NAME);
				break;
			}
		}
		
		// 如果没有找到字段或字段为空数组，使用默认字段
		if (!fields || !Array.isArray(fields) || fields.length === 0) {
			console.log('initFormData - 未找到匹配字段或字段为空，使用默认字段');
			fields = defaultFields;
			
			// 入职审批相关表单 - 涵盖各种可能的ID
			const isRecruitmentForm = (
				normalizedCateId === '6' || numericCateId === 6 || // 入职审批
				normalizedCateId === '11' || numericCateId === 11 || // 招聘审批
				normalizedCateId === '12' || numericCateId === 12 || // 入职流程
				normalizedCateId === '13' || numericCateId === 13 || // 人员入职
				normalizedCateId === '14' || numericCateId === 14 || // 招聘流程
				normalizedCateId === '15' || numericCateId === 15 // 员工入职
			);
			
			if (isRecruitmentForm) {
				// 入职/招聘类通用表单
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '入职申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'dept', title: '入职部门', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'position', title: '入职岗位', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'date', title: '入职日期', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'salary', title: '薪资范围', type: 'select', must: true, select: ['面议', '5k以下', '5k-10k', '10k-15k', '15k-20k', '20k以上'], def: '面议' },
					{ mark: 'education', title: '学历要求', type: 'select', must: true, select: ['不限', '大专', '本科', '硕士', '博士'], def: '本科' },
					{ mark: 'experience', title: '经验要求', type: 'select', must: true, select: ['不限', '1年以下', '1-3年', '3-5年', '5-10年', '10年以上'], def: '不限' },
					{ mark: 'desc', title: '其他说明', type: 'textarea', must: false, len: 500, def: '' },
					{ mark: 'img', title: '简历上传', type: 'image', min: 0, max: 3, must: false, def: [] }
				];
				
				// 根据ID细分不同类型的表单
				if (normalizedCateId === '11' || numericCateId === 11 || normalizedCateId === '14' || numericCateId === 14) {
					// 招聘类表单
					fields[0].def = '招聘申请';
					fields.splice(5, 0, { mark: 'count', title: '招聘人数', type: 'text', must: true, len: 10, def: '1' });
					fields.splice(9, 0, { mark: 'deadline', title: '截止日期', type: 'date', must: true, def: dayjs().add(30, 'day').format('YYYY-MM-DD') });
				}
			} 
			// 请假审批表单
			else if (normalizedCateId === '2' || numericCateId === 2 || normalizedCateId === '4' || numericCateId === 4) {
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '请假申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'type', title: '请假类型', type: 'select', must: true, select: ['事假', '病假', '年假', '调休', '婚假', '产假', '丧假', '其他'], def: '事假' },
					{ mark: 'start', title: '开始时间', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'end', title: '结束时间', type: 'date', must: true, def: dayjs().add(1, 'day').format('YYYY-MM-DD') },
					{ mark: 'days', title: '请假天数', type: 'text', must: true, len: 10, def: '1' },
					{ mark: 'desc', title: '请假事由', type: 'textarea', must: true, len: 500, def: '' }
				];
			} 
			// 报销审批表单
			else if (normalizedCateId === '3' || numericCateId === 3) {
				fields = [
					{ mark: 'title', title: '报销标题', type: 'text', must: true, len: 50, def: '费用报销' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'type', title: '报销类型', type: 'select', must: true, select: ['差旅费', '交通费', '餐饮费', '办公用品', '会议费', '其他'], def: '差旅费' },
					{ mark: 'amount', title: '报销金额', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'date', title: '使用日期', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'desc', title: '报销说明', type: 'textarea', must: true, len: 500, def: '' },
					{ mark: 'img', title: '票据上传', type: 'image', min: 1, max: 8, must: true, def: [] }
				];
			}
			// 其他默认表单根据类型
			else if (normalizedCateId === '7' || numericCateId === 7) {
				// 离职审批
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '离职申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'dept', title: '所在部门', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'position', title: '当前岗位', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'date', title: '离职日期', type: 'date', must: true, def: dayjs().add(30, 'day').format('YYYY-MM-DD') },
					{ mark: 'reason', title: '离职原因', type: 'select', must: true, select: ['个人原因', '家庭原因', '身体原因', '薪资原因', '发展原因', '工作环境', '其他'], def: '个人原因' },
					{ mark: 'desc', title: '详细说明', type: 'textarea', must: true, len: 500, def: '' }
				];
			} else if (normalizedCateId === '8' || numericCateId === 8) {
				// 出差申请
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '出差申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'destination', title: '目的地', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'start', title: '开始日期', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'end', title: '结束日期', type: 'date', must: true, def: dayjs().add(3, 'day').format('YYYY-MM-DD') },
					{ mark: 'days', title: '出差天数', type: 'text', must: true, len: 10, def: '3' },
					{ mark: 'budget', title: '预算金额', type: 'text', must: true, len: 20, def: '' },
					{ mark: 'desc', title: '出差事由', type: 'textarea', must: true, len: 500, def: '' }
				];
			} else if (normalizedCateId === '9' || numericCateId === 9) {
				// 加班申请
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '加班申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'date', title: '加班日期', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'start', title: '开始时间', type: 'text', must: true, len: 10, def: '18:00' },
					{ mark: 'end', title: '结束时间', type: 'text', must: true, len: 10, def: '21:00' },
					{ mark: 'hours', title: '加班小时', type: 'text', must: true, len: 10, def: '3' },
					{ mark: 'type', title: '加班类型', type: 'select', must: true, select: ['工作日加班', '周末加班', '节假日加班'], def: '工作日加班' },
					{ mark: 'desc', title: '加班事由', type: 'textarea', must: true, len: 500, def: '' }
				];
			} else if (normalizedCateId === '10' || numericCateId === 10) {
				// 转正申请
				fields = [
					{ mark: 'title', title: '申请标题', type: 'text', must: true, len: 50, def: '转正申请' },
					{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
					{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'dept', title: '所在部门', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'position', title: '当前岗位', type: 'text', must: true, len: 50, def: '' },
					{ mark: 'entry', title: '入职日期', type: 'date', must: true, def: dayjs().subtract(3, 'month').format('YYYY-MM-DD') },
					{ mark: 'apply', title: '申请日期', type: 'date', must: true, def: dayjs().format('YYYY-MM-DD') },
					{ mark: 'self', title: '自我评价', type: 'textarea', must: true, len: 500, def: '' },
					{ mark: 'plan', title: '工作计划', type: 'textarea', must: true, len: 500, def: '' }
				];
			}
		}
		
		return {
			id,
			fields,
			cateId
		}
	}

	static initFormStepData(id = '') {
		return {
			id,
			fields: projectSetting.FLOW_SETP_FIELDS
		}
	}


	static async delFlow(id, callback) {
		let cb = async () => {
			try {
				let params = {
					id
				}
				let opts = {
					title: '删除中'
				}

				await cloudHelper.callCloudSumbit('flow/del', params, opts).then(res => {
					pageHelper.showSuccToast('删除成功', 1500, callback);
				});
			} catch (err) {
				console.log(err);
			}
		}

		pageHelper.showConfirm('确认删除? 删除不可恢复', cb);
	}
	
	/**
	 * 强制设置登录状态，避免自动退出登录问题
	 * @param {Object} that 页面实例
	 * @param {String} pageName 页面名称，用于日志标识
	 */
	static forceSetLoginState(that, pageName = 'flow_page') {
		console.log(`[${pageName}] 强制设置登录状态`);
		
		// 清除登出标记
		wx.removeStorageSync('MANUAL_LOGOUT');
		wx.removeStorageSync('LOGOUT_FLAG');
		wx.removeStorageSync('LOGOUT_TIME');
		
		// 检查是否有token
		let token = cacheHelper.get(constants.CACHE_TOKEN);
		if (!token) {
			// 如果没有token，则从用户信息中获取并设置
			let userInfo = cacheHelper.get('CCMINI_PROFILE');
			if (userInfo && userInfo.id) {
				// 创建简单token并保存
				let simpleToken = {
					id: userInfo.id,
					name: userInfo.name || '用户',
					dept: userInfo.dept || '',
					status: 1,
					type: 1
				};
				cacheHelper.set(constants.CACHE_TOKEN, simpleToken, constants.CACHE_TOKEN_EXPIRE);
				console.log(`[${pageName}] 已创建临时token:`, simpleToken);
				
				// 尝试获取当前用户详情并更新token
				PassportBiz.getMyDetailWithCache().then(res => {
					if (res && res.id) {
						let fullToken = {
							id: res.id,
							name: res.name || '用户',
							dept: res.dept || '',
							status: 1,
							type: 1,
							phone: res.phone || ''
						};
						cacheHelper.set(constants.CACHE_TOKEN, fullToken, constants.CACHE_TOKEN_EXPIRE);
						console.log(`[${pageName}] 已更新完整token`);
					}
				}).catch(err => {
					console.error(`[${pageName}] 获取用户详情失败:`, err);
				});
			} else {
				// 创建默认token
				let defaultToken = {
					id: 'default_' + dayjs().valueOf(),
					name: '默认用户',
					dept: '',
					status: 1,
					type: 1
				};
				cacheHelper.set(constants.CACHE_TOKEN, defaultToken, constants.CACHE_TOKEN_EXPIRE);
				console.log(`[${pageName}] 已创建默认token:`, defaultToken);
			}
		} else {
			// 刷新token有效期
			cacheHelper.set(constants.CACHE_TOKEN, token, constants.CACHE_TOKEN_EXPIRE);
		}
		
		// 更新页面登录状态
		if (that) {
			that.setData({ isLogin: true });
		}
		
		return true;
	}
}

FlowBiz.CHECK_FORM = {
	forms: 'formForms|array',
};

module.exports = FlowBiz;